package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"hahaha/dao"
	"log"
	"net/http"
	"time"
)

func main() {
	// 初始化数据库
	db, _ := dao.ConnectToDatabase()

	router := gin.Default()
	router.LoadHTMLGlob("sysuser/templates/*.html")

	// 登录页
	router.GET("/index", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", gin.H{
			"title": "登录",
		})
	})

	// 注册页
	router.GET("/register", func(c *gin.Context) {
		c.HTML(http.StatusOK, "register.html", gin.H{
			"title": "注册",
		})
	})

	// 登录
	router.POST("/login", func(c *gin.Context) {
		/*json := make(map[string]interface{}) //注意该结构接受的内容
		c.BindJSON(&json)
		c.JSON(200, gin.H{
			"a": c.Query("a"),
			"b": json["b"],
			"c": json["c"],
		})*/
		doBindIndex(c)
	})

	// 注册
	router.POST("/register", func(c *gin.Context) {
		/*json := make(map[string]interface{}) //注意该结构接受的内容
		c.BindJSON(&json)
		c.JSON(200, gin.H{
			"a": c.Query("a"),
			"b": json["b"],
			"c": json["c"],
		})*/
		doBindRegister(c, db)
	})

	router.Run(":8080")
}

// 定义LoginForm结构体
type LoginUser struct {
	LoginName string `form:"loginName" json:"loginName" binding:"required"`
	Password  string `form:"password" json:"password" binding:"required,min=5"`
}

func doBindIndex(c *gin.Context) {
	var loginUser LoginUser
	err := c.ShouldBind(&loginUser)
	// 如果报错信息不为空
	if err == nil {
		fmt.Printf("UserName:%s,PassWord:%s", loginUser.LoginName, loginUser.Password)
		c.String(http.StatusOK, "submit success!")
	}
}

// 定义RegisterForm结构体
type RegisterUser struct {
	Id            string    `json:"id" gorm:"primaryKey"` // 指定表主键
	LoginName     string    `form:"loginName" json:"loginName" binding:"required"`
	Password      string    `form:"password" json:"password" binding:"required,min=5"`
	UserName      string    `form:"userName" json:"userName" binding:"required"`
	Sex           string    `form:"sex" json:"sex" binding:"required"`
	AccountStatus int       `json:"accountStatus"`
	CreateDate    time.Time `json:"createDate"`
}

func doBindRegister(c *gin.Context, db *gorm.DB) {
	var registerUser RegisterUser
	err := c.ShouldBind(&registerUser)

	if err == nil {
		fmt.Printf("UserName:%s,PassWord:%s", registerUser.LoginName, registerUser.Password)
		//c.String(http.StatusOK, "submit success!")

		registerUser.AccountStatus = 0
		id, _ := uuid.NewUUID()
		registerUser.Id = id.String()
		registerUser.CreateDate = time.Now()
		// 写入数据库
		/*res, err := db.Exec("insert into sys_user (id,login_name,user_name,password,sex,account_status) values (?,?,?,?,?,?)", id.String(),
		registerUser.LoginName, registerUser.UserName, registerUser.Password, registerUser.Sex, registerUser.AccountStatus)*/

		if err := db.Table("go_test.sys_user").Create(&registerUser).Error; err != nil {
			c.JSON(200, gin.H{
				"success": false,
			})
			return
		}

		c.HTML(http.StatusOK, "index.html", gin.H{
			"title": "登录",
		})
	}
}

func checkError(e error) {
	if e != nil {
		log.Fatal(e)
	}
}
